package com.lvy.hczn.front.business.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ByteUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.lvy.hczn.front.business.dto.SortTaskDetailDto;
import com.lvy.hczn.front.business.service.SortTaskDetailService;
import com.lvy.hczn.front.system.domain.business.Model;
import com.lvy.hczn.front.system.domain.business.WcsResponse;
import com.lvy.hczn.front.business.dto.MockResponse;
import com.lvy.hczn.front.business.dto.ToWcs;
import com.lvy.hczn.front.business.service.MqttService;
import com.lvy.hczn.front.business.util.ResultUtil;
import com.lvy.hczn.front.common.exception.UtilException;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

@RequestMapping("/api/dt/mqtt")
@RestController
@Slf4j
public class MqttController {

    @Resource
    private MqttService mqttService;

    @Autowired
    private SortTaskDetailService sortTaskDetailService;

    /**
     * 发送自定义消息内容（使用默认主题）
     *
     * @param msg 消息内容
     * @return com.lvy.hczn.common.core.util.ResultUtil
     * @author yw
     * @date 2022-01-18 20:42:30
     */
    @RequestMapping(value = "/sendMqtt", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResultUtil sendMqtt(@RequestParam(value = "msg") String msg) {

        log.info("================生产默认主题的MQTT消息===={}============", msg);
        Map<String, Object> map = new HashMap<>();
        map.put("name", msg);
        map.put("data", DateUtil.now());
        mqttService.sendToMqtt(JSONUtil.toJsonStr(map));
        return ResultUtil.ok();
    }

    /**
     * 发送自定义消息内容，且指定主题
     *
     * @param topic 主题
     * @param msg   消息内容
     * @return com.lvy.hczn.common.core.util.ResultUtil
     * @author yw
     * @date 2022-01-18 20:42:53
     */
    @RequestMapping(value = "/sendMqttWithTopic", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResultUtil sendMqttWithTopic(@RequestParam("topic") String topic, @RequestParam(value = "msg") String msg) {
        log.info("================生产自定义主题的MQTT消息===={}============", msg);
        List<ToWcs> stFromWms = new ArrayList<>();
        ToWcs fromWms = new ToWcs();
        fromWms.setTempNum(ByteUtil.intToByte(RandomUtil.randomInt(1, 254)));
        fromWms.setBoxCode("LYG" + RandomUtil.randomInt(100000000, 999999999));
        List<Integer> typeList = new ArrayList<>();

        for (int i = 0; i < 100; i++) {
            int type = RandomUtil.randomBigDecimal(BigDecimal.valueOf(1), BigDecimal.valueOf(65)).setScale(2, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(1000)).intValue();
            typeList.add(type);
        }
        fromWms.setPartType(typeList);

        List<Integer> numList = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            int type = RandomUtil.randomBigDecimal(BigDecimal.valueOf(1), BigDecimal.valueOf(65)).setScale(2, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(1000)).intValue();
            numList.add(type);
        }
        fromWms.setPartNum(numList);

        List<Integer> weightList = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            int type = RandomUtil.randomBigDecimal(BigDecimal.valueOf(1), BigDecimal.valueOf(65)).setScale(2, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(1000)).intValue();
            weightList.add(type);
        }
        fromWms.setPartWeight(weightList);
        fromWms.setTotalWeight(RandomUtil.randomBigDecimal(BigDecimal.valueOf(1), BigDecimal.valueOf(65534)).setScale(2, RoundingMode.HALF_UP).intValue());
        fromWms.setState(RandomUtil.randomInt(1, 255));
        System.out.println(JSONUtil.toJsonStr(fromWms));
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        mqttService.sendToMqtt(topic, JSONUtil.toJsonStr(fromWms));

//        mqttService.sendToMqtt(topic, String.valueOf(1));
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return ResultUtil.ok();
    }


    public static void main(String[] args) throws IOException, InterruptedException {
        BigDecimal num = BigDecimal.valueOf(80);
        BigDecimal num1 = BigDecimal.valueOf(-6);
        log.error("---："+(num.subtract(num1.abs())).divide(BigDecimal.valueOf(5), 2, RoundingMode.HALF_UP));
    }


    /**
     * 发送自定义消息内容，且指定主题
     *
     * @param topic 主题
     * @param msg   消息内容
     * @return com.lvy.hczn.common.core.util.ResultUtil
     * @author yw
     * @date 2022-01-18 20:42:53
     */
    @RequestMapping(value = "/test", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResultUtil test(@RequestParam("topic") String topic, @RequestParam(value = "msg") String msg) {
//        while (true){
        Map<String, Object> map = new HashMap<>();
        map.put("OpenDoor_01", false);
//        map.put("T_STRING", RandomUtil.randomBigDecimal(BigDecimal.valueOf(100)).setScale(2, RoundingMode.HALF_UP));
        System.out.println(JSONUtil.toJsonStr(map));
        WcsResponse response = new WcsResponse();
        response.setAnswerID(1);
        response.setBoxCode(msg);
        mqttService.sendToMqtt(topic, JSONUtil.toJsonStr(map));
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
//        }
        return ResultUtil.ok();
    }

    @ApiOperation(value = "消息发送", notes = "消息发送")
    @PostMapping("response")
    public ResultUtil wcsResponse(@RequestBody MockResponse param) {
        try {
            if(!param.getTopic().isEmpty()){
                mqttService.sendToMqtt(param.getTopic(), JSONUtil.toJsonStr(param.getMap()));
            }else{
                return ResultUtil.failed("参数为空");
            }

            /*for (int i = 0; i < 1000000000; i++) {
                Thread.sleep(1000);
                param.getMap().put("Timer",LocalDateTime.now());
                mqttService.sendToMqtt(param.getTopic(),JSONUtil.toJsonStr(param.getMap()));
            }*/
            return ResultUtil.ok();
        } catch (Exception e) {
            if (e instanceof UtilException) {
                return ResultUtil.failed(e.getMessage());
            } else {
                return ResultUtil.failed("系统异常");
            }
        }
    }

    @RequestMapping(value = "/sort/weight", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResultUtil test(HttpServletRequest request, @RequestBody SortTaskDetailDto sortTaskDetail) {
        try {
            sortTaskDetailService.updateSortWeightById(request, sortTaskDetail, sortTaskDetail.getBoxCode(), sortTaskDetail.getSortIds());
            return ResultUtil.ok();
        }catch (Exception e){
            if (e instanceof UtilException) {
                return ResultUtil.failed(e.getMessage());
            } else {
                return ResultUtil.failed("系统异常");
            }
        }
    }
}
